﻿using System.Collections.Generic;
using System.Linq;

namespace Tuxedo.Compile
{
	internal class ForeachLoop : CodeLine
	{
		public UnverifiedType Type { get; private set; }
		public string VariableName { get; private set; }
		public Expression IterableExpression { get; private set; }
		public CodeLine[] Code { get; private set; }

		public ForeachLoop(UnverifiedType type, string varName, Expression iterableExpression, IList<CodeLine> code)
		{
			this.Type = type;
			this.VariableName = varName;
			this.IterableExpression = iterableExpression;
			this.Code = code.ToArray();
		}

		public static ForeachLoop Parse(TokenStream tokens)
		{
			tokens.PopExpected("foreach");
			tokens.PopExpected("(");
			UnverifiedType type = UnverifiedType.Parse(tokens, false);
			string varName = tokens.PopIdentifier();
			tokens.PopExpected("in");
			Expression iterableExpression = Expression.ParseExpression(tokens, false);
			tokens.PopExpected(")");
			IList<CodeLine> code = CodeLine.ParseBlock(tokens, false);
			return new ForeachLoop(type, varName, iterableExpression, code);
		}
	}
}
